        import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { defineMessages, intlShape, injectIntl, FormattedMessage } from 'react-intl'
import { createForm } from 'rc-form'
import { Switch, Modal, Popover, Icon, InputItem, Toast } from 'antd-mobile'
import { NewMarketOrder2 } from 'component/position'
import {
  messages,
  MarketShowItem,
  MarketBtnItem,
  PriceItem,
  OffsetItem,
  SelectPopValid,
  MarketNameItem,
  NewGoodsAndNum
} from './'
import Reflux from 'reflux'
import { PriceAction } from '../../actions'
import { PriceStore } from '../../stores'
import { helper, config, myFetch } from 'component/utils'

const alert = Modal.alert

const Item = Popover.Item

class GoodsAndNum extends Component {
  state = {
    visible: false,
    visible1: false,
    value: this.props.defaultNum || '40',
    present: this.props.present
  }
  onSelect = (opt) => {
    let one = messages[helper.splitString(opt.props.value)[0]]
    let two = messages[helper.splitString(opt.props.value)[1]]
    let present = this.props.formatMessage(one) + '/' + this.props.formatMessage(two)
    this.setState({
      visible: false,
      present: present
    }, () => {
      this.props.topSelected(opt.props.value)
      PriceAction.clearTimeout()
      PriceAction.changePrice(opt.props.value, helper.accMul(this.state.value, 1000))
    })
  }
  onSelect1 = (opt) => {
    this.setState({
      visible1: false,
      value: opt.props.value
    }, () => {
      this.props.numValue(opt.props.value)
      PriceAction.clearTimeout()
      PriceAction.changePrice(opt.props.value, helper.accMul(this.state.value, 1000))
    })
  }
  onOverlay = (data) => {
    if (data == 'undefined') {
      data = []
      return data
    }
    let result = []
    result = data.map((val, index) => {
      return <Item key={index} value={val.ccyPair}>
        {val.name}
      </Item>
    })
    return result
  }
  handleVisibleChange = (visible) => {
    if (this.onOverlay(this.props.data).length < 1) {
      return
    }
    this.setState({visible})
  }
  handleVisibleChange1 = (visible) => {
    this.setState({
      visible1: visible
    })
  }
  onChange = (val) => {
    this.setState({
      value: val
    }, () => {
      this.props.numValue(val)
      PriceAction.clearTimeout()
      PriceAction.changePrice(opt.props.value, this.state.value)
    })
  }
  render() {
    console.log(this.props.present, 'present')
    const { data } = this.props
    const { getFieldProps } = this.props.form
    return (
      <div className="rt-select-goodsandnum-alert">
        <div className="rt-selectone">
          <span className="-left">
            {this.props.goods}
          </span>
          <span className="-center">
            {this.state.present}
          </span>
          <Popover
            visible={this.state.visible}
            overlay={this.onOverlay(data)}
            overlayClassName="rt-popover-change"
            onVisibleChange={
              this.handleVisibleChange
            }
            placement='bottom'
            popupAlign={{
              overflow: { adjustY: 0, adjustX: 0 },
              offset: [0, 15],
            }}
            onSelect={this.onSelect}
          >
            <span className="-right">
              <Icon type="down"/>
            </span>
          </Popover>
        </div>
        <div className="rt-selectone">
          <span className="-left">
            {this.props.num}
          </span>
          <span className="rt-select-inner">
            <InputItem
              {
                ...getFieldProps('number',{
                  initialValue: '',
                })
              }
              type="number"
              onChange={this.onChange}
              value={this.state.value}
            />
          <span className="-num-bottom">
            <Icon type={require('static/svg/mul.svg')}/>
            1000{helper.splitString(this.state.present)[0]}
          </span>
          </span>
          <Popover
             visible={this.state.visible1}
             overlay={[
               (<Item key="1" value={10}>10</Item>),
               (<Item key="2" value={20}>20</Item>),
               (<Item key="3" value={50}>50</Item>),
               (<Item key="4" value={100}>100</Item>),
               (<Item key="5" value={200}>200</Item>)
             ]}
             onVisibleChange={
               this.handleVisibleChange1
             }
             onSelect={
               this.onSelect1
             }
           >
             <span className="-right">
               <Icon type="down"/>
             </span>
           </Popover>
        </div>
      </div>
    )
  }
}

const AlertSelectGoodsAndNum = createForm()(GoodsAndNum)
class PositionDirection extends Reflux.Component {
  constructor(props) {
    super(props)
    this.store = PriceStore
    this.storeKeys = ['sellPrice', 'buyPrice']
  }
  render() {
    const { className, val } = this.props
    return (
      <div className="rt-position-direction">
        <div className={`-left ${className} ? ${className} : ''`}>
          {this.props.formatMessage(messages[this.props.direction])}
        </div>
        <div>
          {this.props.formatMessage(messages['currentPrice'])}
          :
          <span className="-price">{val == 0 ? this.state.sellPrice : this.state.buyPrice }元</span>
        </div>
      </div>
    )
  }
}

class TradeMarket extends Reflux.Component {
  constructor(props) {
    super(props)
    this.state = {
      active: 1,
      value: 40,
      valueAlert: 0,
      direction: 0,
      limitCheck: false,
      stopCheck: false,
      rateCheck: false,
      offsetNum: props.present.includes('JPY') ? 0.01 : 0.0001,
      validity: 0,
      present: props.present
    }
    this.store = PriceStore
    this.storeKeys = ['sellPrice', 'buyPrice', 'highPrice', 'lowPrice', 'openPrice', 'bidPriceVar', 'askPriceVar']
  }
  onConfirmClick = (val) => {
    //console.log(val, 'val')
    const str = this.props.intl.formatMessage(messages.alertName)
    const goods = this.props.intl.formatMessage(messages.goods)
    const num = this.props.intl.formatMessage(messages.num)
    let one = messages[helper.splitString(this.props.present)[0]]
    let two = messages[helper.splitString(this.props.present)[1]]
    let present = this.props.intl.formatMessage(one) + '/' + this.props.intl.formatMessage(two)

    let title = <span>{str}</span>
    let data = JSON.parse(localStorage.ccy)
    data = data.map((val, index) => {
    let result = {}
    let one = messages[helper.splitString(val.ccyPair)[0]]
    let two = messages[helper.splitString(val.ccyPair)[1]]
    result.name = this.props.intl.formatMessage(one) + '/' + this.props.intl.formatMessage(two)
    result.ccyPair = val.ccyPair
    return result
    })
    alert(title, 
      <div>
        <AlertSelectGoodsAndNum
          goods={goods}
          num={num}
          data={data}
          present={present}
          topSelected={this.props.topSelected}
          numValue={this.numValue1}
          formatMessage={this.props.intl.formatMessage}
          defaultNum={this.state.value}
        />
        <PositionDirection
          direction={val == 0 ? 'sell' : 'buy'}
          formatMessage={this.props.intl.formatMessage}
          price={val == 0 ? this.state.sellPrice : this.state.buyPrice}
          val={val}
          className={val == 1 ? '-green' : ''}
        />
      </div>, [
      { text: '取消', onPress: () => console.log('cancel') },
      { text: '确定', onPress: () => {
        this.onPositionConfirm(val)
        }
      }
    ])
  }
  onPositionConfirm = (val) => {
    let amount = 0
    if (this.state.valueAlert == 0) {
      amount = this.state.value
    } else {
      amount = this.state.valueAlert
    }
    let offset = {}
    let length = 10000
    if (this.props.present.includes('JPY')) {
      length = 100
    }
    if (this.state.rateCheck) {
      if (val == 0) {
        offset.PRIC = this.state.sellPrice
      } else if (val == 1) {
        offset.PRIC = this.state.buyPrice
      }
      //offset.SLRG = helper.accMul(this.state.offsetNum, length)
      offset.SLRG = helper.accMul(this.state.offsetNum, length)
    }
    const options = {
      method: 'POST',
      body: JSON.stringify({
        OFLG: 1,
        PAIR: this.props.present,
        BSKB: val,
        AMNT: helper.accMul(amount, 1000),
        SKJK: this.state.rateCheck ? 2 : 1,
        ...offset,
        //...limitdata,
        //...stopdata,
        //...timedata
      })
    }
    myFetch(`${config.rootApi}/mOrdermarket`, options, true)
    .then((rs) => {
      if (rs) {
        Toast.success('下单成功')
      }
    })
  }
  /*topSelected = (val) => {
    //console.log(val, 1000)
    this.setState({
      present: val,
    })
  }*/
  numValue1 = (val) => {
    this.setState({
      valueAlert: val
    }, () => {
      PriceAction.clearTimeout()
      PriceAction.changePrice(this.props.present, helper.accMul(val, 1000))
    })
  }
  numValue = (val) => {
    this.setState({
      value: val
    }, () => {
      this.props.number(val)
      PriceAction.clearTimeout()
      PriceAction.changePrice(this.props.present, helper.accMul(val, 1000))
    })
  }
  onOrderPrice = () => {
    let orderPrice 
    if (this.state.direction == 0) {
      orderPrice = this.state.sellPrice
    } else if (this.state.direction == 1 ) {
      orderPrice = this.state.buyPrice
    }
    return orderPrice
  }
  onTimesChangeLimit = (e, num) => {
    this.setState({
      pric: num
    })
  }
  onTimesChangeStop = (e, num) => {
    this.setState({
      pric1: num
    })
  }
  onValidity = (e) => {
    this.setState({
      validity: helper.requestTime(e)
    })
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.present != this.props.present) {
      let result = 0.0001
      if (nextProps.present.includes('JPY')) {
        result= 0.01
      }
      this.setState({
        offsetNum : result
      })
    }  
  }
  onOffsetChange = (e) => {
    console.log(e , 'e')
    this.setState({
      offsetNum: e
    })
  }
  componentDidMount() {
    PriceAction.changePrice(this.props.present, helper.accMul(this.state.value, 1000))
  }
  componentWillUnmount() {
    PriceAction.clearTimeout()
  }
  render() {
    const { getFieldProps } = this.props.form
    const { limitCheck, stopCheck, offsetNum, rateCheck } = this.state
    let diffRate = helper.accMul(helper.accDiv(helper.accSub(this.state.sellPrice, this.state.openPrice), this.state.sellPrice), 100).toFixed(2)
    return (
      <div className="rt-padding-24 rt-bg-white">
        <NewGoodsAndNum
          present={this.props.present}
          numValue={this.numValue}
        />
        <MarketNameItem />
        <MarketBtnItem
          askPriceVar={this.state.askPriceVar}
          bidPriceVar={this.state.bidPriceVar}
          sellPrice={this.state.sellPrice}
          buyPrice={this.state.buyPrice}
          length={this.props.length}
          onClick={
            this.onConfirmClick
          }
        />
        <MarketShowItem
          highPrice={this.state.highPrice}
          lowPrice={this.state.lowPrice}
          diffPrice={helper.accSub(this.state.sellPrice, this.state.openPrice)}
          diffRatePrice={diffRate}
        />
        <div className="rt-market-condition">
          <div className={`-item-wrap ${rateCheck ? '-active':'' } `}>
            <div className="-item">
              <FormattedMessage id="distance"/>
              <Switch
                {...getFieldProps('rate', {
                  initialValue: false,
                  valuePropName: 'checked',
                })}
                onClick={
                  (checked) => { 
                    this.setState({
                      rateCheck: checked
                    }) 
                  }
                }
              />
            </div>
            {
            rateCheck ? (
              <OffsetItem
                present={this.props.present}
                num={offsetNum}
                onChange={this.onOffsetChange}
              />
              ) : null
          }
          </div>
          
          
          
        </div>
      </div>
    )
  }
}
TradeMarket.propType = {
  intl: intlShape.isRequired
}
export default injectIntl(createForm()(TradeMarket))